package com.idopartx.phonelightning.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;


import com.idopartx.phonelightning.R;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class PermissionUtils {
    public static final String TAG = "permission_guide";
    public static boolean isHuaWeiDevice() {
        if (Build.MANUFACTURER.equalsIgnoreCase("huawei") || Build.MANUFACTURER.equalsIgnoreCase("honor") || isHarmonyOs())
            return true;
        else
            return false;
    }

    public static boolean isMeiZuDevice(){
        return Build.MANUFACTURER.equalsIgnoreCase("meizu");
    }

    public static Boolean isVivoDevice() {
        return Build.MANUFACTURER.equalsIgnoreCase("vivo");
    }

    public static Boolean isOppoDevice() {
        return Build.MANUFACTURER.equalsIgnoreCase("oppo");
    }

    public static Boolean isXiaomiDevice() {
        return Build.MANUFACTURER.equalsIgnoreCase("xiaomi");
    }

    public static Boolean isHarmonyOs() {
        try {
            Class cls = Class.forName("ohos.utils.system.SystemCapability");
            return cls != null;
        } catch (Exception ex) {
            return false;
        }
    }

    /**悬浮窗**/
    public static boolean isFloatViewPermission(Context context){
        if(isVivoDevice() && Build.VERSION_CODES.M < 26){   //因 VIVO 8.0以下设备不论是否有权限都会返回true，所以改为每次都将其验证为false
            return false;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(context)) {
            return false;
        }else {
            return true;
        }
    }

    /***悬浮窗***/
    public static void startFloatViewPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (isVivoDevice()) {
                context.startActivity(getVivoSettingIntent(context));
            } else {
                context.startActivity(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.getPackageName())));
            }
        }
    }

    public static Intent getVivoSettingIntent(Context context) {
        Intent intent = new Intent();
        intent.putExtra("packagename", context.getPackageName());
        try {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                PackageInfo pkg = context.getApplicationContext().getPackageManager().getPackageInfo(context.getApplicationContext().getPackageName(), 0);
                String appName = pkg.applicationInfo.loadLabel(context.getApplicationContext().getPackageManager()).toString();
                intent.putExtra("title", appName);
                return intent.setComponent(ComponentName.unflattenFromString("com.vivo.permissionmanager/.activity.SoftPermissionDetailActivity"));
            } else {
                Intent localIntent = new Intent();
                localIntent.setClassName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.PurviewTabActivity");
                localIntent.putExtra("packagename", context.getPackageName());
                localIntent.putExtra("tabId", "1");
                return localIntent;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /************************************************************************************************************************************/
                                            /******************自启动权限****************/
    /**********************************************************************************************************************************/

    public static void startAutoStartSetting(Context context) {
        Log.e("Util", "******************当前手机型号为：" + Build.MANUFACTURER);
        Set<Map.Entry<String, List<String>>> entries = autoIntentHashMap.entrySet();
        for (Map.Entry<String, List<String>> entry : entries) {
            String manufacturer = entry.getKey();
            List<String> actCompatList = entry.getValue();
            if (Build.MANUFACTURER.equalsIgnoreCase(manufacturer)) {
                for (String act : actCompatList) {
                    try {
                        Intent intent;
                        if (act.contains("/")) {
                            intent = new Intent();
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            ComponentName componentName = ComponentName.unflattenFromString(act);
                            intent.setComponent(componentName);
                        } else {
                            //所以我是直接跳转到对应的安全管家/安全中心
                            intent = context.getPackageManager().getLaunchIntentForPackage(act);
                        }
                        context.startActivity(intent);
                        break;
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e(TAG, Build.MANUFACTURER + "自启动跳转失败:" + act + e.getMessage());
                    }
                }
            }
        }
    }

    private static HashMap<String, List<String>> autoIntentHashMap = new HashMap<String, List<String>>() {
        {
            put("Xiaomi", Arrays.asList(
                    "com.miui.securitycenter/com.miui.permcenter.autostart.AutoStartManagementActivity",
                    "com.miui.securitycenter"
            ));
            put("samsung", Arrays.asList(
                    "com.samsung.android.sm_cn/com.samsung.android.sm.ui.ram.AutoRunActivity",
                    "com.samsung.android.sm_cn/com.samsung.android.sm.ui.appmanagement.AppManagementActivity",
                    "com.samsung.android.sm_cn/com.samsung.android.sm.ui.cstyleboard.SmartManagerDashBoardActivity",
                    "com.samsung.android.sm_cn/.ui.ram.RamActivity",
                    "com.samsung.android.sm_cn/.app.dashboard.SmartManagerDashBoardActivity",

                    "com.samsung.android.sm/com.samsung.android.sm.ui.ram.AutoRunActivity",
                    "com.samsung.android.sm/com.samsung.android.sm.ui.appmanagement.AppManagementActivity",
                    "com.samsung.android.sm/com.samsung.android.sm.ui.cstyleboard.SmartManagerDashBoardActivity",
                    "com.samsung.android.sm/.ui.ram.RamActivity",
                    "com.samsung.android.sm/.app.dashboard.SmartManagerDashBoardActivity",

                    "com.samsung.android.lool/com.samsung.android.sm.ui.battery.BatteryActivity",
                    "com.samsung.android.sm_cn",
                    "com.samsung.android.sm"
            ));
            put("HUAWEI", Arrays.asList(
                    "com.huawei.systemmanager/.startupmgr.ui.StartupNormalAppListActivity",
                    "com.huawei.systemmanager/.appcontrol.activity.StartupAppControlActivity",
                    "com.huawei.systemmanager/.optimize.process.ProtectActivity",
                    "com.huawei.systemmanager/.optimize.bootstart.BootStartActivity",
                    "com.huawei.systemmanager"
            ));
            put("HONOR", Arrays.asList(
                    "com.hihonor.systemmanager/com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity",
                    "com.huawei.systemmanager/.startupmgr.ui.StartupNormalAppListActivity",
                    "com.huawei.systemmanager/.appcontrol.activity.StartupAppControlActivity",
                    "com.huawei.systemmanager/.optimize.process.ProtectActivity",
                    "com.huawei.systemmanager/.optimize.bootstart.BootStartActivity",
                    "com.hihonor.systemmanager/com.huawei.systemmanager.mainscreen.MainScreenActivity",
                    "com.huawei.systemmanager"
            ));
            put("vivo", Arrays.asList(
                    "com.iqoo.secure/.ui.phoneoptimize.BgStartUpManager",
                    "com.iqoo.secure/.safeguard.PurviewTabActivity",
                    "com.vivo.permissionmanager/.activity.BgStartUpManagerActivity",
//                    "com.iqoo.secure/.ui.phoneoptimize.AddWhiteListActivity", //这是白名单, 不是自启动
                    "com.iqoo.secure",
                    "com.vivo.permissionmanager"
            ));
            put("Meizu", Arrays.asList(
                    "com.meizu.safe/.permission.SmartBGActivity",
                    "com.meizu.safe/.permission.PermissionMainActivity",
                    "com.meizu.safe"
            ));
            put("OPPO", Arrays.asList(
//                    "com.coloros.oppoguardelf/com.coloros.powermanager.fuelgaue.PowerAppsBgSetting",
                    "com.coloros.safecenter/.startupapp.StartupAppListActivity",
                    "com.coloros.safecenter/.permission.startup.StartupAppListActivity",
                    "com.oppo.safe/.permission.startup.StartupAppListActivity",
                    "com.coloros.oppoguardelf/com.coloros.powermanager.fuelgaue.PowerUsageModelActivity",
                    "com.coloros.safecenter/com.coloros.privacypermissionsentry.PermissionTopActivity",
//                    "com.coloros.oppoguardelf/com.coloros.powermanager.fuelgaue.PowerControlActivity",
//                    "com.coloros.phonemanager/com.coloros.phonemanager.FakeActivity",
                    "com.coloros.safecenter",
                    "com.oppo.safe",
                    "com.coloros.oppoguardelf"
            ));
            put("oneplus", Arrays.asList(
                    "com.oneplus.security/.chainlaunch.view.ChainLaunchAppListActivity",
                    "com.oneplus.security"
            ));
            put("letv", Arrays.asList(
                    "com.letv.android.letvsafe/.AutobootManageActivity",
                    "com.letv.android.letvsafe/.BackgroundAppManageActivity",
                    "com.letv.android.letvsafe"
            ));
            put("zte", Arrays.asList(
                    "com.zte.heartyservice/.autorun.AppAutoRunManager",
                    "com.zte.heartyservice"
            ));
            //金立
            put("F", Arrays.asList(
                    "com.gionee.softmanager/.MainActivity",
                    "com.gionee.softmanager"
            ));
            //以下为未确定(厂商名也不确定)
            put("smartisanos", Arrays.asList(
                    "com.smartisanos.security/.invokeHistory.InvokeHistoryActivity",
                    "com.smartisanos.security"
            ));
            //360
            put("360", Arrays.asList(
                    "com.yulong.android.coolsafe/.ui.activity.autorun.AutoRunListActivity",
                    "com.yulong.android.coolsafe"
            ));
            //360
            put("ulong", Arrays.asList(
                    "com.yulong.android.coolsafe/.ui.activity.autorun.AutoRunListActivity",
                    "com.yulong.android.coolsafe"
            ));
            //酷派
            put("coolpad"/*厂商名称不确定是否正确*/, Arrays.asList(
                    "com.yulong.android.security/com.yulong.android.seccenter.tabbarmain",
                    "com.yulong.android.security"
            ));
            //联想
            put("lenovo"/*厂商名称不确定是否正确*/, Arrays.asList(
                    "com.lenovo.security/.purebackground.PureBackgroundActivity",
                    "com.lenovo.security"
            ));
            put("htc"/*厂商名称不确定是否正确*/, Arrays.asList(
                    "com.htc.pitroad/.landingpage.activity.LandingPageActivity",
                    "com.htc.pitroad"
            ));
            //华硕
            put("asus"/*厂商名称不确定是否正确*/, Arrays.asList(
                    "com.asus.mobilemanager/.MainActivity",
                    "com.asus.mobilemanager"
            ));
            //酷派
            put("YuLong", Arrays.asList(
                    "com.yulong.android.softmanager/.SpeedupActivity",
                    "com.yulong.android.security/com.yulong.android.seccenter.tabbarmain",
                    "com.yulong.android.security"
            ));
        }
    };

    /************************************************************************************************************************************/
                                    /******************引导至耗电管理****************/
    /**********************************************************************************************************************************/

    //引导电池耗电管理
    public static void startVivoPowerSetting(Context context) {
        Log.e("Util", "******************当前手机型号为：" + Build.MANUFACTURER);
        if (Build.MANUFACTURER.equalsIgnoreCase("vivo")) {
            Intent localIntent = new Intent();
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.iqoo.powersaving", "com.iqoo.powersaving.PowerSavingManagerActivity");
            context.startActivity(localIntent);
        } else if (Build.MANUFACTURER.equalsIgnoreCase("oppo")) {
            startAppDetailSetting(context);
        }
    }

    /***应用信信进 引导至耗电管理*/
    public static void startOppoPowerManager(Context context) {
        try {
            Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("packageName", context.getPackageName());
            ComponentName comp = new ComponentName("com.coloros.oppoguardelf", "com.coloros.powermanager.fuelgaue.PowerAppsBgSetting");//R9SK 6.0.1  os-v3.0
//            ComponentName comp = new ComponentName("com.coloros.securitypermission", "com.coloros.securitypermission.permission.PermissionAppAllPermissionActivity");//R11t 7.1.1 os-v3.2
            intent.setComponent(comp);
            context.startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "PowerAppsBgSetting 无法跳转:" + e.getMessage());
            startAppDetailSetting(context);
        }
    }

    public static void startAppDetailSetting(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        try {
            context.startActivity(localIntent);
        } catch (Exception e) {
            Log.e(TAG, Build.MANUFACTURER + "应用信息页跳转失败:" + e.getMessage());
        }
    }


    /***跳转系统原生的忽略电池白名单***/
    public static void startWhiteList(Context context) {
        Log.e("whitelist", Build.MANUFACTURER);
        if (Build.MANUFACTURER.equalsIgnoreCase("OPPO") || Build.MANUFACTURER.equalsIgnoreCase("VIVO")
                || Build.MANUFACTURER.equalsIgnoreCase("XIAOMI")
                || Build.MANUFACTURER.equalsIgnoreCase("HUAWEI")
                || Build.MANUFACTURER.equalsIgnoreCase("HONOR")) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                Intent intent = new Intent();
                String packageName = context.getPackageName();
                PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            if (pm.isIgnoringBatteryOptimizations(packageName))
//                intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
//            else {
                    intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                    intent.setData(Uri.parse("package:" + packageName));
//            }
                }
                context.startActivity(intent);
            }
        }
    }

    public static void startXiaoMiBackRun(Context cxt){
        try {
            Intent intent = new Intent(cxt.getPackageName());
            ComponentName componentName = new ComponentName("com.miui.powerkeeper", "com.miui.powerkeeper.ui.HiddenAppsConfigActivity");
            intent.setComponent(componentName);
            intent.putExtra("package_name", cxt.getPackageName());
            intent.putExtra("package_label", cxt.getResources().getString(R.string.app_name));
            cxt.startActivity(intent);
        }catch (Exception exception){
            startWhiteList(cxt);
        }

    }
}
